import { createRouter, createWebHistory } from 'vue-router'
import {getToken } from '@/utils/token'
import {msgOpen} from '@/utils/msg'
import { mainStore } from '@/stores/store'
import {filterRoute} from '@/utils/filterRoute'
import {nextTick} from 'vue'
//导入Login组件
import Login from "@/views/Login.vue"

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
const routes = [
  {
      path: '/',
      redirect: '/xfjc/login'
  },
  {
      path: '/xfjc/login',
      name:"Login",
      component: Login 
  },
  {
    path:'/404',
    name: '404page',
    component: ()=>import("@/views/404.vue")//懒加载 
  },
  {
    path:'/:pathMacth(.*)',
    redirect: '/404',
  },
  {
      path: '/xfjc/index',
      name:"index",
      component: ()=>import("@/views/Index.vue")//懒加载 
  },

]
// 3. 创建路由实例并传递 `routes` 配置
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

//4.前置路由守卫
router.beforeEach(async (to, from, next) => {  
  if(to.path == '/xfjc/login' || to.path == '/'){
    next()
  }else{
    //没有登录，强制跳转登录页
    const token  = getToken()
    if(!token && (to.path !== '/xfjc/login'|| to.path !== '/')){
      msgOpen("请先登录")
      return next({path:'/xfjc/login'})
    }
    //重复登录
    if(token && (to.path == '/xfjc/login'|| to.path == '/')){
      msgOpen("请勿重复登录")
      // console.log(from);    
      return next({path:from.path ? from.path : '/xfjc/login'})
    }
    //前往主页
    if(token ){
      if(to.path === '/xfjc/index'){
        /*
        这里在获取 pinia 中数据时,先执行了await nextTick();是因为此时如果直接拿 pinia 中数据是拿不到的,因为 pinia 还没有初始化完毕
        */
        await nextTick()
        const useStore = mainStore()
        //添加路由
        let xfjcIndex = routes.filter(v=>v.path == '/xfjc/index')[0]  //找到需要添加子级的父路由 
        xfjcIndex.children = []
        let routeData = filterRoute(useStore.menuList)
        xfjcIndex.children = routeData
        router.addRoute(xfjcIndex)
        // console.log(router.getRoutes());  
      }  
      next()
    }
  } 
  
})

//#region 
/*  
路由懒加载时，component如果使用变量，打包时的静态分析则无法匹配到具体的路由
//动态children处理
function setRoutes(arr){
  let xfjcIndex = routes.filter(v=>v.path == '/xfjc/index')[0]   
  xfjcIndex.children = []
  let res = routesTree(arr)
  // console.log(res);
  xfjcIndex.children = res
  return xfjcIndex
}
//递归route
function routesTree(data){ 
   
  let routesArr = []   //该变量不可在外部声明
  // const recom = {template: `<router-view></router-view>`}//多级路由时，父级没有页面时使用，防止路由跳级
  const recom = {template: `<router-view v-slot="{ Component }">
                                  <keep-alive>
                                      <component :is="Component" />
                                  </keep-alive>
                              </router-view>`
                  }
  data.forEach((item) => {
      if(item.nextLev){
          routesArr.push({
              path: item.PATH,
              name: item.COMPONENTNAME,
              component: item.REMARK == "链接" ? ()=>import(`@/views/${item.DIRNAME}/${item.COMPONENTNAME}.vue`) : recom,
              componentPath:item.REMARK == "链接" ? `@/views/${item.DIRNAME}/${item.COMPONENTNAME}.vue` 
                                              : "{template: `<router-view></router-view>`}",
              meta:item.REMARK == "链接" ? {keepAlive:true} : {keepAlive:false},//缓存
              children:routesTree(item.nextLev)
          })
      }else{
          routesArr.push({
              path: item.PATH,
              name: item.COMPONENTNAME,
              component: item.REMARK == "链接" ? ()=>import(`@/views/${item.DIRNAME}/${item.COMPONENTNAME}.vue`) : recom,
              componentPath:item.REMARK == "链接" ? `@/views/${item.DIRNAME}/${item.COMPONENTNAME}.vue` 
                                                  : "{template: `<router-view></router-view>`}",
              meta:item.REMARK == "链接" ? {keepAlive:true} : {keepAlive:false},
          })
      }
  })
  // console.log(routesArr);    
  return routesArr
}
*/
//#endregion

export default router
